package com.flying.fish.manage.rest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.flying.fish.formwork.base.BaseRest;
import com.flying.fish.formwork.util.ApiResult;
import com.flying.fish.formwork.util.Constants;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @Description 用户登录控制器
 * @Author MR
 * @Date 2021/07/14
 * @Version V1.0
 */
@RestController
public class LoginRest extends BaseRest {

    @Resource
    private RedisTemplate redisTemplate;
    public static final String USER_NAME = "gateway";
    public static final String USER_PASSWD = "gateway";

    @Data
    public static class FishUser {
        private String userName;
        private String userPasswd;
        private LocalDateTime time;
    }


    /**
     * 登录
     * @return
     */
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public ApiResult login(@RequestBody FishUser fishUser){
        if (USER_NAME.equals(fishUser.userName) && USER_PASSWD.equals(fishUser.getUserPasswd())) {
            String token = MD5Utils.md5Hex("gateway" + System.currentTimeMillis(), String.valueOf(StandardCharsets.UTF_8));
            fishUser.setUserPasswd(null);
            fishUser.setTime(LocalDateTime.now());
            redisTemplate.opsForValue().set("TOKEN:" + token, JSONObject.toJSONString(fishUser), 12, TimeUnit.HOURS);
            return new ApiResult(Constants.SUCCESS, token);
        }
        return new ApiResult(Constants.FAILED, "用户名密码错误", null);
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping(value = "/logout", method = {RequestMethod.GET})
    public ApiResult logout(@RequestHeader(value = "token", required = false) String token) {
        if (StringUtils.isBlank(token)) {
            return new ApiResult();
        }
        redisTemplate.delete(String.format("TOKEN:%s", token));
        return new ApiResult(Constants.SUCCESS);
    }

}
